import axios, {type AxiosRequestConfig, type AxiosResponse} from 'axios'
import cookie from 'js-cookie'
import qs from 'qs'
import router from "@/router";
import { ElMessage } from 'element-plus'
import { useUserStore } from "@/stores/admin";
import NProgress from "nprogress"

declare interface TypeResponse extends AxiosResponse {
  errno: number,
  errmsg: string
}
let baseURL = '';
if (process.env.NODE_ENV === 'development') {
  baseURL = '/api'
} else {
  baseURL = "http://zxwyit.cn:8080/m.api";
}

//创建axios实列
const instance = axios.create({
  baseURL,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  timeout: 500
})

//添加请求拦截器
instance.interceptors.request.use((config:AxiosRequestConfig) => {
  if (config.headers) {
    NProgress.start()
    config.headers['AdminToken'] = cookie.get('token') + '';
  }
  return config;
}, function (error) {
  console.error("请求错误", error)
})

const METHOD_TYOE = [ '_mt=edit', '_mt=create', '_mt=delete', '_mt=update']

//添加响应拦截器
instance.interceptors.response.use(async (res) => {
   console.log(555,res);
  // 对响应数据做点什么
  let data = res.data
  let { errno, errmsg } = data
  let path = router.currentRoute.value.fullPath  //获取当前的路由路劲
  if (10006 == errno) {
    //获取接口请求数据
    const configData = res.config.data
    //判断METHOD_TYOE是否包含上次请求的类型
    var index = METHOD_TYOE.findIndex(item=>configData.includes(item))  
    //请求类型是否为无痛刷新类型 index!==-1 需要无痛刷新
    if(-1===index){ //需要重新登录获取令牌
      ElMessage.error(errmsg)
      router.replace({ path: '/login', query: { back: path } }) //登录后需要跳回的地址
      return;
    }else{ //需要无痛刷新令牌
      const store = useUserStore(); //获取状态管理的数据
      const { username,password} = store.loginInfo
      //重新获取令牌
      const loginDate = {_gp:'admin',_mt:'login',username,password}
      const { errno, errmsg, data } = await post(loginDate)  //这里需要同步获取
      if(200==errno){
        cookie.set('token',data) //保存令牌
      }else{
        router.replace({ path: '/login', query: { back: path } }) //登录后需要跳回的地址
        console.log(store.loginInfo);
        return Promise.reject({errno,errmsg,data})
      }
      //重新发送上次请求
      return instance.request(res.config)
    }
  } 
  NProgress.done()
  return data
}, function (error) {
  // 对响应错误做点什么
  console.error("请求响应错误", error)
  return Promise.reject(error)
})

function get(params?: object): Promise<TypeResponse> {
  return instance.get('', { params });
}

function post(data: object, params?: object): Promise<TypeResponse> {
  return instance.post('', qs.stringify(data), { params });
}
// 富文本图片请求
export function upload(data: object): Promise<TypeResponse> {
  return instance.post("../upload/admin", data);
}
export { 
  get, 
  post 
}